// pages/login/login.js
import config from '../../utils/config';

const defaultAvatarUrl = 'https://huibanhao.com.cn/default-avatar.png'
Page({

  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: '未登录',
    },
    phoneNumber: '',
    verifyCode: '',
    canSendCode: false,
    sendCodeText: '发送验证码',
    countdown: 60,
    noticeInfo: {
      show: false,
      content: '',
      color: {
        background: '#FDF2F0',
        border: '#F7CEC8',
        text: '#EC5B56'
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getNoticeInfo();
  },

  /**
   * 获取通知信息
   */
  getNoticeInfo() {
    wx.request({
      url: `${config.baseUrl}/notify`,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data && res.data.data.success) {
          this.setData({
            noticeInfo: {
              show: true,
              content: res.data.data.content,
              color: res.data.data.color
            }
          });
        }
      },
      fail: (err) => {
        console.log('获取通知信息失败:', err);
        // 接口失败时不显示通知
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  onGetUserInfo(e) {
    if (e.detail.userInfo) {
      this.setData({
        userInfo: e.detail.userInfo
      });
    }
  },
  
  onGetPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      const code = e.detail.code; // 获取code
    
      wx.request({
        url: `${config.baseUrl}/getAppletAccessToken`,
        method: 'POST',
        success: res => {
          if (res.statusCode !== 200) return;
          const access_token = res.data.data.access_token;
          wx.request({
            url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${access_token}`,
            method: 'POST',
            data: {
              code
            },
            success: data => {
              if (data.statusCode !== 200) return;
              if (!data.data || !data.data.phone_info) {
                console.error('获取手机号失败', data);
                return;
              }
              const { phoneNumber } = data.data.phone_info; // 这里就是获取到的手机号
              this.setData({
                phoneNumber: phoneNumber, // 更新 phoneNumber
                canSendCode: this.isValidPhoneNumber(phoneNumber) // 同时更新发送按钮状态
              });
            }
          });
        }
      });
    } else {
      console.error('获取手机号失败', e.detail.errMsg);
    }
  },

  navigateToRegister: function() {
    wx.navigateTo({
      url: '/pages/register/register'
    });
  },

  // 手机号输入处理
  onPhoneInput(e) {
    const phoneNumber = e.detail.value;
    this.setData({
      phoneNumber,
      canSendCode: this.isValidPhoneNumber(phoneNumber)
    });
  },

  // 验证手机格式
  isValidPhoneNumber(phone) {
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
  },

  // 发送验证码
  async sendVerifyCode() {
    if (!this.isValidPhoneNumber(this.data.phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }
    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${config.baseUrl}/sendVerifyCode`,
          method: 'POST',
          data: {
            phoneNumber: this.data.phoneNumber
          },
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });

      if (res.data.code === 200) {
        this.startCountdown();
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: res.data.message || '发送失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error(error);
      wx.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      });
    }
  },

  // 开始倒计时
  startCountdown() {
    this.setData({
      canSendCode: false,
      countdown: 60
    });

    const timer = setInterval(() => {
      if (this.data.countdown <= 0) {
        clearInterval(timer);
        this.setData({
          canSendCode: true,
          sendCodeText: '获取验证码'
        });
        return;
      }

      this.setData({
        countdown: this.data.countdown - 1,
        sendCodeText: `${this.data.countdown}秒后重试`
      });
    }, 1000);
  },

  // 验证码输入处理
  onVerifyCodeInput(e) {
    this.setData({
      verifyCode: e.detail.value
    });
  },

  // 登录处理
  async handleLogin() {
    // 验证表单
    if (!this.data.phoneNumber || !this.data.verifyCode) {
      wx.showToast({
        title: '请填写手机号和验证码',
        icon: 'none'
      });
      return;
    }

    if (!this.isValidPhoneNumber(this.data.phoneNumber)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    wx.login({
      success (res) {
        wx.request({
          url: `${config.baseUrl}/getAppletOpenId`,
          method: "POST",
          data: {
            code: res.code
          },
          success: (res) => {
            console.log(res)
            wx.setStorageSync('openId', res.data.data.openid);
          }
        })
      }
    })

    try {
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: `${config.baseUrl}/login`,
          method: 'POST',
          data: {
            phoneNumber: this.data.phoneNumber,
            verifyCode: this.data.verifyCode
          },
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });

      if (res.data.code === 200) {
        // 存储token和用户信息
        wx.setStorageSync('token', res.data.data.token);
        wx.setStorageSync('userInfo', res.data.data.userInfo);

        wx.showToast({
          title: '登录成功',
          icon: 'success'
        });

        // 登录成功后跳转
        setTimeout(() => {
          const redirectInfo = wx.getStorageSync('redirectAfterLogin');
          if (redirectInfo && redirectInfo.url) {
            wx.removeStorageSync('redirectAfterLogin');
            const pages = getCurrentPages();
            if (pages.length > 1) {
              wx.navigateBack();
            } else {
              wx.redirectTo({ url: redirectInfo.url });
            }
          } else {
            wx.reLaunch({ url: '/pages/profile/profile' });
          }
        }, 1500);
      } else {
        wx.showToast({
          title: res.data.msg || '登录失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error(error);
      wx.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    }
  },
})